<template>
  <div>
    <h1>{{ id ? '编辑' : '新建' }}广告位</h1>
    <el-form label-width="100px">
      <el-row type="flex" style="jus">
        <el-col>
          <el-form-item label="广告位名称">
            <el-input v-model="model.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col style="margin-left:8rem">
          <el-button @click="model.items.push({})"> <i class="el-icon-plus"></i>添加广告</el-button>
        </el-col>
      </el-row>
      <!-- <el-form-item label=""> -->
      <!-- 广告位的每个广告 -->
      <el-row style="hieght:100px;align-items: center;" type="flex" v-for="(item, i) in model.items" :key="i">
        <el-col>
          <el-form-item label="url">
            <el-input v-model="item.url"></el-input>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="">
            <el-upload class="avatar-uploader" :action="uploadUrl" :headers="getAuthHeaders()" :show-file-list="false" :on-success="(res) => $set(item, 'image', res.url)">
              <img v-if="item.image" style="height:5rem;width:5rem" :src="item.image" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <!-- </el-row> -->
        </el-col>
        <el-col>
          <el-form-item>
            <el-button size="small" type="danger" @click="model.items.splice(i, 1)">删除</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- </el-form-item> -->

      <el-form-item>
        <el-button type="primary" native-type="submit" @click="save">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    id: {},
  },
  data() {
    return {
      url: 'http://192.168.135.114:3000/admin/api/upload',
      model: {
        items: [],
      },
    };
  },

  created() {
    this.id && this.fetch();
  },

  methods: {
    async save() {
      if (!this.model.name) {
        this.$message({
          showClose: true,
          message: '请填写分类',
        });
        return;
      }
      let res;
      let message = '';
      // 根据id的有无 判断是新增还是修改
      if (this.id) {
        res = await this.axios.put(`rest/ads/${this.id}`, this.model);
        message = '修改成功';
      } else {
        res = await this.axios.post('rest/ads', this.model);
        message = '添加 成功';
      }

      this.$message({
        showClose: true,
        message: message,
        type: 'success',
      });

      setTimeout(() => {
        this.$router.push('/ads/list');
      }, 500);
    },

    async fetch() {
      const res = await this.axios.get(`rest/ads/${this.id}`);
      this.model = res.data;
    },
  },
};
</script>
<style scoped></style>;
